package cn.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;

import cn.entity.Page;
import cn.entity.User;
import cn.service.IUserService;
import cn.service.impl.UserService;
import cn.util.DateUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

@SuppressWarnings("serial")
public class UserAction extends HttpServlet {
	private Configuration cfg = null;

	@Override
	public void init() throws ServletException {
		cfg = new Configuration();
		cfg.setServletContextForTemplateLoading(this.getServletContext(), null);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		// 网站全路径
		String basePath = req.getScheme() + "://" + req.getServerName() + ":"
				+ req.getServerPort() + req.getContextPath() + "/";
		// 得到要操作的方法名
		String method = req.getParameter("method");

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("path", basePath);
		// 设置编码
		res.setContentType("text/html;charset=utf-8");
		// 得到输出流
		PrintWriter out = res.getWriter();
		Template t = null;
	
		// 查询所有用户/模糊查询
		if (method.equals("queryAll")) {
			try {
				this.doQueryAll(req, res, map);
			} catch (Exception e) {
				e.printStackTrace();
			}
			t = cfg.getTemplate("WEB-INF/templates/index.ftl");
			System.out.println("已输出");

		}
		// 添加用户前的跳转
		if (method.equals("forwardSave")) {
			t = cfg.getTemplate("WEB-INF/templates/form.ftl");
		}
		// 保存用户
		if (method.equals("save")) {
			System.out.println("save");
			try {
				this.doSave(req, res);
			} catch (Exception e) {
				e.printStackTrace();
			}
			res.sendRedirect(req.getContextPath()+"/UserAction?method=queryAll");
			return;
		}
		// 删除用户
		if (method.equals("delete")) {
			try {
				this.doDel(req, res);
			} catch (Exception e) {
				e.printStackTrace();
			}
			res.sendRedirect(req.getContextPath()+"/UserAction?method=queryAll");
			return;
		}
		// 更新用户前的跳转
		if (method.equals("forwardUpdate")) {
			Integer u_id = Integer.parseInt(req.getParameter("u_id"));
			UserService userService = new UserService();
			User user = new User();
			user.setU_id(u_id);
			try {
				user = userService.findOne(user);
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
			map.put("user", user);
			t = cfg.getTemplate("WEB-INF/templates/update.ftl");
		}
		// 更新用户
		if (method.equals("update")) {
			try {
				this.doUpdate(req, res);
			} catch (Exception e) {
				e.printStackTrace();
			}
			res.sendRedirect(req.getContextPath()+"/UserAction?method=queryAll");
			return;
		}
		try {
			// 处理map和输出流
			
			t.process(map, out);
			out.flush();
			out.close();
		} catch (TemplateException e) {
			e.printStackTrace();
		}

	}
	

	private void doQueryAll(HttpServletRequest req, HttpServletResponse res, Map<String, Object> map)
			throws Exception {
		req.setCharacterEncoding("utf-8");
		String page = req.getParameter("page");
		String rows = req.getParameter("rows");
		
		String u_id = req.getParameter("u_id");
		String u_name = req.getParameter("u_name");
		String u_type = req.getParameter("u_type");
		String starTime = req.getParameter("starTime");
		String endTime = req.getParameter("endTime");
		System.out.println("---------------参数"+u_id+u_name+u_type+starTime+endTime);
		if(page == null || page.trim().length()==0){
			page = "1";
		}
		if(rows == null || rows.trim().length()==0){
			rows = "4";
		}
		int currPageNo = Integer.parseInt(page);
		int perPageSize = Integer.parseInt(rows);
		User user = new User();;
		IUserService userService = new UserService();
		Page<?> pagebean = null;
		
			 if(u_name!=null && u_name.trim().length()>0 ){
				 System.out.println("参数为setU_name！"+u_name);
				 user.setU_name(u_name);
						
				}
			 if(u_id!=null && u_id.trim().length()>0){
		    	 System.out.println("参数为setU_id！"+u_id);
				 user.setU_id(Integer.parseInt(u_id));
				 
			 	}
			 if(u_type!=null && u_type.trim().length()>0){
				 if(Integer.parseInt(u_type)>=0){
				 System.out.println("参数为setU_type！"+u_type); 
				 user.setU_type(Integer.parseInt(u_type));
				 }
				}
			 pagebean = userService.showUsersByCondition(currPageNo, perPageSize, user); 
			 if(starTime!=null && endTime!=null && starTime.trim().length()>0 && endTime.trim().length()>0){
					 	System.err.println("参数为时期型！");
						  pagebean = userService.showUsersByTime(currPageNo, perPageSize, starTime, endTime); 
			 }
		map.put("use", user);
		map.put("users", pagebean.gettList());
		map.put("page", pagebean.getCurrPageNo());
		map.put("allPage", pagebean.getAllPageNo());
	}

	private void doUpdate(HttpServletRequest req, HttpServletResponse res) throws Exception {
		req.setCharacterEncoding("utf-8");
		Integer u_id = Integer.parseInt(req.getParameter("u_id"));
		String u_name = req.getParameter("u_name");
		String u_remarks = req.getParameter("u_remarks");
		Integer u_state = Integer.parseInt(req.getParameter("u_state"));
		String u_createtime = req.getParameter("u_createtime");
		String u_lastonline = req.getParameter("u_lastonline");
		Integer u_type = Integer.parseInt(req.getParameter("u_type"));
		IUserService userService = new UserService();
		User user = new User();
		user.setU_id(u_id);
		user.setU_name(u_name);
		user.setU_remarks(u_remarks);
		user.setU_state(u_state);
		user.setU_createtime(DateUtil.getDate(u_createtime, "yyyy-MM-dd HH:mm:ss"));
		user.setU_lastonline(DateUtil.getDate(u_lastonline, "yyyy-MM-dd HH:mm:ss"));
		user.setU_type(u_type);
		userService.update(user);
	}
	
	private void doDel(HttpServletRequest req, HttpServletResponse res) throws Exception {
		req.setCharacterEncoding("utf-8");
		Integer u_id = Integer.parseInt(req.getParameter("u_id"));
		IUserService userService = new UserService();
		userService.delete(u_id);
	}

	private void doSave(HttpServletRequest req, HttpServletResponse res) throws Exception {
		req.setCharacterEncoding("utf-8");
		String u_name = req.getParameter("u_name");
		String u_remarks = req.getParameter("u_remarks");
		Integer u_state = Integer.parseInt(req.getParameter("u_state"));
		String u_createtime = req.getParameter("u_createtime");
		String u_lastonline = req.getParameter("u_lastonline");
		Integer u_type = Integer.parseInt(req.getParameter("u_type"));
		IUserService userService = new UserService();
		User user = new User();
		user.setU_name(u_name);
		user.setU_remarks(u_remarks);
		user.setU_state(u_state);
		user.setU_createtime(new Date());
		user.setU_lastonline(new Date());
		user.setU_type(u_type);
		userService.add(user);
		System.out.println("添加完成！");

	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		doGet(req, res);
	}
}
